package up_down_share.library;

import java.io.BufferedInputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.lang.reflect.Method;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLEncoder;
import java.nio.ByteBuffer;
import java.text.SimpleDateFormat;
import java.util.Locale;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlarmManager;
import android.app.AlertDialog;
import android.app.NotificationManager;
import android.app.SearchManager;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.hardware.SensorManager;
import android.location.LocationManager;
import android.media.AudioManager;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.os.Message;
import android.os.PowerManager;
import android.os.Vibrator;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.WindowManager;
import android.view.accessibility.AccessibilityManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.ImageView;
import android.widget.ImageView.ScaleType;
import android.widget.Toast;





// ----------------------------------------------------------------------------------------------------
// ----- Utility -----
// ----------------------------------------------------------------------------------------------------
public class Utility
{
	// --------------------------------------------------
	// ----- constants -----
	// --------------------------------------------------
	public static final String ENCODING_USASCII = "US-ASCII";
	public static final String ENCODING_ISO88591 = "ISO-8859-1";
	public static final String ENCODING_UTF8 = "UTF-8";
	public static final String ENCODING_BIG5 = "BIG5";
	public static final String ENCODING_GBK = "GBK";
	public static final int TRUE = 1;
	public static final int FALSE = 0;
	public static final String LOG_DEBUG = "Debug";

	// --------------------------------------------------
	// ----- functions -----
	// --------------------------------------------------
	public static void log(final Class classObject, final String logString)
	{
		Log.d(LOG_DEBUG, String.format("%s %s", classObject.getSimpleName(), logString));
	}

	public static void log(final Class classObject, final String logString, final Exception exception)
	{
		Log.e(LOG_DEBUG, String.format("%s %s", classObject.getSimpleName(), logString), exception);
	}

	public static void debugDeviceInformation(final Activity activity)
	{
		// log(Utility.class, String.format("Device Unique ID: %s", Build.DEVICE)); // needs TelephonyManager.
		log(Utility.class, String.format("Device Name: %s", Build.PRODUCT));
		log(Utility.class, String.format("Model: %s", Build.MODEL));
		log(Utility.class, String.format("System Version: %s", Build.VERSION.RELEASE));
		log(Utility.class, String.format("Display width: %d", getDisplayWidth(activity)));
		log(Utility.class, String.format("Display height: %d", getDisplayHeight(activity)));
		log(Utility.class, String.format("Display ratio: %f", getDisplayRatio(activity)));
		log(Utility.class, String.format("Display density: %f", getDisplayMetrics(activity).density));

		log(Utility.class, String.format("OS version: %d", android.os.Build.VERSION.SDK_INT));
	}

	public static void debugAllMethod(final Class classObject)
	{
		Log.d(LOG_DEBUG, classObject.getName());
		final Method[] methodArray = classObject.getMethods();
		for (final Method method : methodArray)
		{
			Log.d(LOG_DEBUG, method.getName());
		}
	}

	public static void debugAllMethod(final String className)
	{
		try
		{
			final Class classObject = Class.forName(className);
			debugAllMethod(classObject);
		}
		catch (final Exception ex)
		{
			Utility.log(Utility.class, "Throws exception (debugAllMethod).", ex);
		}
	}

	public static void call(final Activity activity, final String number)
	{
		// <uses-permission android:name="android.permission.CALL_PHONE" />
		final Intent intent = new Intent(Intent.ACTION_CALL);
		intent.setData(Uri.parse(String.format("tel:%s", number)));
		activity.startActivity(intent);
	}

	public static AlertDialog createAlertDialog(final Context context)
	{
		final View view = new View(context);
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		alertDialogBuilder.setView(view);
		return alertDialogBuilder.create();
	}

	public static AlertDialog createAlertDialog(final Context context, final int layoutID)
	{
		final View view = Utility.getView(context, layoutID);
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		alertDialogBuilder.setView(view);
		return alertDialogBuilder.create();
	}

	public static AlertDialog createAlertDialog(final Context context, final View view)
	{
		final AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(context);
		alertDialogBuilder.setView(view);
		return alertDialogBuilder.create();
	}

	public static MarginLayoutParams createMarginLayoutParams(final int width, final int height, final int topMargin, final int bottomMargin, final int leftMargin, final int rightMargin)
	{
		final MarginLayoutParams marginLayoutParams = new MarginLayoutParams(width, height);
		marginLayoutParams.setMargins(leftMargin, topMargin, rightMargin, bottomMargin);
		return marginLayoutParams;
	}

	public static Message createMessage(final int what, final Bundle extraBundle)
	{
		return createMessage(what, -1, -1, null, extraBundle);
	}

	public static Message createMessage(final int what, final int arg1, final int arg2, final Object object)
	{
		return createMessage(what, arg1, arg2, object, null);
	}

	public static Message createMessage(final int what, final int arg1, final int arg2, final Object object, final Bundle extraBundle)
	{
		final Message message = new Message();
		message.what = what;
		message.arg1 = arg1;
		message.arg2 = arg2;
		message.obj = object;
		message.setData(extraBundle);
		return message;
	}

	public static boolean deleteFile(final File file)
	{
		// ----- directory. -----
		if (file != null && file.isDirectory())
		{
			final String[] filePathArray = file.list();
			for (final String element : filePathArray)
			{
				final boolean isDeleted = deleteFile(new File(file, element));
				if (!isDeleted)
				{
					return false;
				}
			}
		}
		// ----- deletes. -----
		return file.delete();
	}

	public static void dial(final Activity activity)
	{
		final Intent intent = new Intent(Intent.ACTION_DIAL);
		activity.startActivity(intent);
	}

	public static String escapeRegex(final String string)
	{
		String escapedString = string;
		escapedString = escapedString.replace("\\", "\\\\");
		escapedString = escapedString.replace(".", "\\.");
		escapedString = escapedString.replace("[", "\\[");
		escapedString = escapedString.replace("]", "\\]");
		escapedString = escapedString.replace("(", "\\(");
		escapedString = escapedString.replace(")", "\\)");
		escapedString = escapedString.replace("^", "\\^");
		escapedString = escapedString.replace("$", "\\$");
		escapedString = escapedString.replace("?", "\\?");
		escapedString = escapedString.replace("+", "\\+");
		escapedString = escapedString.replace("|", "\\|");
		return escapedString;
	}

	public static AccessibilityManager getAccessibilityManager(final Context context)
	{
		return (AccessibilityManager) context.getSystemService(Context.ACCESSIBILITY_SERVICE);
	}

	public static ActivityManager getActivityManager(final Context context)
	{
		return (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
	}

	public static AlarmManager getAlarmManager(final Context context)
	{
		return (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
	}

	public static AudioManager getAudioManager(final Context context)
	{
		return (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
	}

	public static Bitmap getBitmap(final String urlString)
	{
		try
		{
			final int DEFAULT_BUFFERSIZE = 1024;
			Bitmap bitmap = null;
			final InputStream inputStream = new BufferedInputStream(new URL(urlString).openStream(), DEFAULT_BUFFERSIZE);
			bitmap = BitmapFactory.decodeStream(inputStream);
			inputStream.close();
			return bitmap;
		}
		catch (final Exception ex)
		{}
		return null;
	}

	public static float getBrightness(final Activity activity)
	{
		final WindowManager.LayoutParams layoutParams = activity.getWindow().getAttributes();
		return layoutParams.screenBrightness;
	}

	public static File getCacheDirectory()
	{
		final File directory = new File(getDataDirectory(), "cache");
		directory.mkdir();
		return directory;
	}

	public static ClipboardManager getClipboardManager(final Context context)
	{
		return (ClipboardManager) context.getSystemService(Context.CLIPBOARD_SERVICE);
	}

	public static ConnectivityManager getConnectivityManager(final Context context)
	{
		return (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
	}

	public static File getDataDirectory()
	{
		return Environment.getDataDirectory();
	}

	public static SimpleDateFormat getDateFormatter()
	{
		return getFormatter("yyyy-MM-dd");
	}

	public static SimpleDateFormat getDateTimeFormatter()
	{
		return getFormatter("yyyy-MM-dd HH:mm:ss");
	}

	public static int getDisplayHeight(final Activity activity)
	{
		final Display display = activity.getWindowManager().getDefaultDisplay();
		return display.getHeight();
	}

	public static DisplayMetrics getDisplayMetrics(final Activity activity)
	{
		final Display display = activity.getWindowManager().getDefaultDisplay();
		final DisplayMetrics displayMetrics = new DisplayMetrics();
		display.getMetrics(displayMetrics);
		return displayMetrics;
	}

	public static float getDisplayRatio(final Activity activity)
	{
		return (float) getDisplayWidth(activity) / getDisplayHeight(activity);
	}

	public static int getDisplayWidth(final Activity activity)
	{
		final Display display = activity.getWindowManager().getDefaultDisplay();
		return display.getWidth();
	}

	public static File getDownloadCacheDirectory()
	{
		return Environment.getDownloadCacheDirectory();
	}

	public static File getExternalStorageDirectory()
	{
		return Environment.getExternalStorageDirectory();
	}

	public static SimpleDateFormat getFileDateFormatter()
	{
		return getFormatter("yyyyMMdd");
	}

	public static SimpleDateFormat getFileDateTimeFormatter()
	{
		return getFormatter("yyyyMMddHHmmss");
	}

	public static SimpleDateFormat getFormatter(final String formatString)
	{
		return new SimpleDateFormat(formatString);
	}

	public static SimpleDateFormat getFormatter(final String formatString, final Locale locale)
	{
		return new SimpleDateFormat(formatString, locale);
	}

	public static InputMethodManager getInputMethodManager(final Context context)
	{
		return (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
	}

	public static LayoutInflater getLayoutInflater(final Context context)
	{
		return (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
	}

	public static LocationManager getLocationManager(final Context context)
	{
		return (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);
	}

	public static NotificationManager getNotificationManager(final Context context)
	{
		return (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
	}

	public static long getNow()
	{
		return System.currentTimeMillis();
	}

	public static PowerManager getPowerManager(final Context context)
	{
		return (PowerManager) context.getSystemService(Context.POWER_SERVICE);
	}

	public static File getRootDirectory()
	{
		return Environment.getRootDirectory();
	}

	public static SearchManager getSearchManager(final Context context)
	{
		return (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
	}

	public static SensorManager getSensorManager(final Context context)
	{
		return (SensorManager) context.getSystemService(Context.SENSOR_SERVICE);
	}

	public static float getStreamVolume(final Context context)
	{
		final AudioManager audioManager = up_down_share.library.Utility.getAudioManager(context);
		return ((float) audioManager.getStreamVolume(AudioManager.STREAM_MUSIC) / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
	}

	public static void setStreamVolume(final Context context, final float volume)
	{
		final AudioManager audioManager = up_down_share.library.Utility.getAudioManager(context);
		audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, (int) (volume * audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC)), 0);
	}

	public static String getString(final File file, final String encodingString) throws IOException
	{
		final FileInputStream fileInputStream = new FileInputStream(file);
		return getString(fileInputStream, encodingString);
	}

	public static String getString(final InputStream inputStream, final String encodingString) throws IOException
	{
		final InputStreamReader inputStreamReader = new InputStreamReader(inputStream, ENCODING_ISO88591);
		final BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
		final StringBuilder stringBuilder = new StringBuilder();
		String lineString = null;
		while ((lineString = bufferedReader.readLine()) != null)
		{
			stringBuilder.append(String.format("%s\n", lineString));
		}
		bufferedReader.close();
		return new String(stringBuilder.toString().getBytes(ENCODING_ISO88591), encodingString);
	}

	public static String getString(final String urlString, final String encodingString, final int timeout) throws ClientProtocolException, IOException
	{
		final HttpParams httpParams = new BasicHttpParams();
		HttpConnectionParams.setConnectionTimeout(httpParams, timeout);
		HttpConnectionParams.setSoTimeout(httpParams, timeout);
		final HttpGet httpGet = new HttpGet(urlString);
		final DefaultHttpClient defaultHttpClient = new DefaultHttpClient(httpParams);
		final HttpResponse httpResponse = defaultHttpClient.execute(httpGet);

		return getString(httpResponse.getEntity().getContent(), encodingString);
	}

	public static String getString(final URL url, final String encodingString, final int timeout) throws ClientProtocolException, IOException
	{
		final String safeURLString = String.format("%s://%s%s?%s", url.getProtocol(), url.getHost(), url.getPath(), URLEncoder.encode(url.getQuery(), Utility.ENCODING_UTF8));
		return getString(safeURLString, encodingString, timeout);
	}

	public static TelephonyManager getTelephonyManager(final Context context)
	{
		return (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
	}

	public static SimpleDateFormat getTimeFormatter()
	{
		return getFormatter("HH:mm:ss");
	}

	public static Vibrator getVibrator(final Context context)
	{
		return (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
	}

	public static View getView(final Context context, final int layoutID)
	{
		return Utility.getLayoutInflater(context).inflate(layoutID, null);
	}

	public static WifiManager getWIFIManager(final Context context)
	{
		return (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
	}

	public static WindowManager getWindowManager(final Context context)
	{
		return (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
	}

	public static void log(final File file, final String message)
	{
		try
		{
			final FileOutputStream fileOutputStream = new FileOutputStream(file, true);
			final OutputStreamWriter outputStreamWriter = new OutputStreamWriter(fileOutputStream);
			// ----- writes. -----
			outputStreamWriter.write(message + "\r\n");
			outputStreamWriter.flush();
			outputStreamWriter.close();
		}
		catch (final Exception ex)
		{}
	}

	public static void openAndroidMarket(final Activity activity, final String searchString)
	{
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		final String urlString = String.format("market://search?q=%s", searchString);
		intent.setData(Uri.parse(urlString));
		activity.startActivity(intent);
	}

	public static void openApplicationForSendingMessage(final Activity activity, final String title, final String subject, final String message)
	{
		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("text/plain");
		intent.putExtra(Intent.EXTRA_SUBJECT, subject);
		intent.putExtra(Intent.EXTRA_TEXT, message);
		activity.startActivity(Intent.createChooser(intent, title));
	}

	public static void openAudio(final Activity activity, final String title, final String uriString)
	{
		final String adjustedURIString = (uriString.startsWith("file://") || uriString.startsWith("http://")) ? uriString : String.format("file://%s", uriString);
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(adjustedURIString), "audio/*");
		activity.startActivity(Intent.createChooser(intent, title));
	}

	public static void openGoogleMap(final Activity activity, final double latitude, final double longitude, final int zoomLevel)
	{
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(String.format("geo:%f,%f?z=%d", latitude, longitude, zoomLevel)));
		activity.startActivity(intent);
	}

	public static void openGoogleMap(final Activity activity, final String locationString, final int zoomLevel)
	{
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(String.format("geo:0,0?q=%sz=%d", locationString, zoomLevel)));
		activity.startActivity(intent);
	}

	public static void openGoogleSearch(final Activity activity, final String queryString)
	{
		final Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
		intent.putExtra(SearchManager.QUERY, queryString);
		activity.startActivity(intent);
	}

	public static void openGoogleStreetView(final Activity activity, final double latitude, final double longitude)
	{
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(String.format("google.streetview:cbll=%f,%f&cbp=1,%d,,%d,%f", latitude, longitude, 0, 180, 1.0)));
		activity.startActivity(intent);
	}

	public static void openImage(final Activity activity, final String title, final String uriString)
	{
		final String adjustedURIString = (uriString.startsWith("file://") || uriString.startsWith("http://")) ? uriString : String.format("file://%s", uriString);
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(adjustedURIString), "image/*");
		activity.startActivity(Intent.createChooser(intent, title));
	}

	public static void openMail(final Activity activity, final String title, final String to, final String subject, final String body)
	{
		final Intent intent = new Intent(Intent.ACTION_SEND);
		intent.setType("plain/text");
		intent.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
		intent.putExtra(Intent.EXTRA_SUBJECT, subject);
		intent.putExtra(Intent.EXTRA_TEXT, body);
		activity.startActivity(Intent.createChooser(intent, title));
	}

	public static void openVideo(final Activity activity, final String title, final String uriString)
	{
		final String adjustedURIString = (uriString.startsWith("file://") || uriString.startsWith("http://")) ? uriString : String.format("file://%s", uriString);
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.parse(adjustedURIString), "video/*");
		activity.startActivity(Intent.createChooser(intent, title));
	}

	public static void openWebBrowser(final Activity activity, final String urlString)
	{
		final String adjustedURLString = urlString.startsWith("http://") ? urlString : String.format("http://%s", urlString);
		final Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setData(Uri.parse(adjustedURLString));
		activity.startActivity(intent);
	}

	public static void prompt(final Context context, final int resourceID)
	{
		prompt(context, context.getResources().getString(resourceID));
	}

	public static void prompt(final Context context, final String message)
	{
		Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
	}

	public static String readAll(final File file)
	{
		final StringBuffer stringBuffer = new StringBuffer();
		try
		{
			final FileInputStream fileInputStream = new FileInputStream(file);
			int oneByte;
			while ((oneByte = fileInputStream.read()) != -1)
			{
				stringBuffer.append((char) oneByte);
			}
			fileInputStream.close();
		}
		catch (final Exception ex)
		{}
		return stringBuffer.toString();
	}

	public static void rotateImageView(final ImageView imageView, final Bitmap bitmap, final float degree)
	{
		try
		{
			final Matrix matrix = new Matrix();
			matrix.postScale(((float) imageView.getWidth() / bitmap.getWidth()), ((float) imageView.getHeight() / bitmap.getHeight()));
			matrix.postRotate(degree);
			final Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
			imageView.setImageBitmap(rotatedBitmap);
			imageView.setScaleType(ScaleType.CENTER);
		}
		catch (final Exception ex)
		{}
	}

	public static double round(final double unrounded, final int precision, final int roundingMode)
	{
		final BigDecimal bigDecimal = new BigDecimal(unrounded);
		final BigDecimal rounded = bigDecimal.setScale(precision, roundingMode);
		return rounded.doubleValue();
	}

	public static Bitmap scaleBitmap(final Bitmap bitmap, final float scaleFactor)
	{
		try
		{
			if (bitmap != null)
			{
				final Matrix matrix = new Matrix();
				matrix.postScale(scaleFactor, scaleFactor);
				final Bitmap scaledBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
				return scaledBitmap;
			}
		}
		catch (final Exception ex)
		{}
		return bitmap;
	}

	public static void setBrightness(final Activity activity, final float brightnessLevel)
	{
		// range: 0.0 to 1.0.
		final float brightnessLevelMin = 0.05f; // prevents to be dark.
		final float adjustedBrightnessLevel = Math.max(brightnessLevel, brightnessLevelMin);
		final WindowManager.LayoutParams layoutParams = activity.getWindow().getAttributes();
		layoutParams.screenBrightness = adjustedBrightnessLevel;
		activity.getWindow().setAttributes(layoutParams);
	}

	public static short convertByteToShort(final byte byte01, final byte byte02)
	{
		final ByteBuffer byteBuffer = ByteBuffer.allocate(2);
		byteBuffer.put(byte01);
		byteBuffer.put(byte02);
		return byteBuffer.getShort(0);
	}

	public static int convertByteToInt(final byte byte01, final byte byte02, final byte byte03, final byte byte04)
	{
		final ByteBuffer byteBuffer = ByteBuffer.allocate(4);
		byteBuffer.put(byte01);
		byteBuffer.put(byte02);
		byteBuffer.put(byte03);
		byteBuffer.put(byte04);
		return byteBuffer.getInt(0);
	}

	public static long convertByteToLong(final byte byte01, final byte byte02, final byte byte03, final byte byte04, final byte byte05, final byte byte06, final byte byte07, final byte byte08)
	{
		final ByteBuffer byteBuffer = ByteBuffer.allocate(8);
		byteBuffer.put(byte01);
		byteBuffer.put(byte02);
		byteBuffer.put(byte03);
		byteBuffer.put(byte04);
		byteBuffer.put(byte05);
		byteBuffer.put(byte06);
		byteBuffer.put(byte07);
		byteBuffer.put(byte08);
		return byteBuffer.getLong(0);
	}

	public static String convertByteArrayToHEXString(final byte[] byteArray, final int length)
	{
		final StringBuffer hexStringBuffer = new StringBuffer();
		for (int i = 0; i < length; i++)
		{
			final int intValue = byteArray[i] & 0xff;
			if (intValue < 0x10)
			{
				hexStringBuffer.append("0");
			}
			hexStringBuffer.append(Integer.toHexString(intValue));
			hexStringBuffer.append(" ");
		}
		return hexStringBuffer.toString();
	}

	public static String unescape(String string)
	{
		while (true)
		{
			final int tokenIndex = string.indexOf("&#");
			if (tokenIndex < 0)
			{
				break;
			}
			final int valueIndex = string.indexOf(";", tokenIndex + 2);
			if (valueIndex < 0)
			{
				break;
			}
			try
			{
				string = string.substring(0, tokenIndex) + (char) (Integer.parseInt(string.substring(tokenIndex + 2, valueIndex))) + string.substring(valueIndex + 1);
			}
			catch (final Exception e)
			{
				return string;
			}
		}
		string = string.replace("&quot;", "\"");
		string = string.replace("&lt;", "<");
		string = string.replace("&gt;", ">");
		string = string.replace("&amp;", "&");
		return string;
	}

	public static void wakeUp(final Context context)
	{
		final PowerManager.WakeLock wakeLock = Utility.getPowerManager(context).newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, context.getClass().getName());
		wakeLock.acquire();
		wakeLock.release();
	}

	public static void writeAll(final File file, final byte[] byteArray) throws IOException
	{
		final FileOutputStream fileOutputStream = new FileOutputStream(file);
		fileOutputStream.write(byteArray);
		fileOutputStream.flush();
		fileOutputStream.close();
	}

	public static int getWidthPixels(final Activity mActivity)
	{
		final DisplayMetrics dm = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		final int width = dm.widthPixels;
		return width;
	}

	public static float getDisplayScale(final Activity mActivity)
	{
		final DisplayMetrics dm = new DisplayMetrics();
		mActivity.getWindowManager().getDefaultDisplay().getMetrics(dm);
		final float density = dm.density;
		return density;
	}
}
